<?php
// 配置类型模型
class CatModel extends Model {
	
	 private $catdata;  //分类数组
	 
	  //获得指定类型的顺序分类
    public function getTypeCats($type=0){
    	//获得所有顺序分类
    	$cdata = $this->getAllCats();
    	$i = 0;
    	$temp = array();
    	foreach($cdata as $value){
    		if($value['type'] == $type){
    			
    			$temp[$i] = $value;
    			$i++;
    			
    		}
    	}
    	
    	return $temp;
    }
    
    
    //根据栏目id获得栏目数据
    public function getCatById($id){
    	$cdata = $this->getAllCats();
    	foreach($cdata as $value){
    		if($value['id'] == $id){
    			
    			return $value;
    			
    		}
    	}
    }
    
    //根据栏目编号获得所有父栏目
    public function getCatPcat($id){
    	$cdata = $this->getAllCats();
    	$temp = array();
    	foreach($cdata as $key=>$value){
    		if($value['id'] == $id){
    			array_push($temp,$value);
    			$pid = $value['pid'];
    			//循环找到当前类
    			if($key>0){
	    			for($i=$key-1;$i>=0;$i--){
	    				if($pid==$cdata[$i]['id']){
	    					$pid=$cdata[$i];
	    					array_push($temp,$cdata[$i]);
	    			  }
	    				if($cdata[$i]['pid']==0){
	    					return array_reverse($temp);
	    				}
	    			}
	    		}
    			return array_reverse($temp);
    			
    		}
    	}
    }
    
    //根据目录获得栏目数据
    public function getCatByMulu($mulu){
    	$cdata = $this->getAllCats();
    	foreach($cdata as $value){
    		if($value['directory'] == $mulu){
    			
    			return $value;
    			
    		}
    	}
    	
    }
    
    //根据父栏目获得所有子栏目
    public function getCatsByPid($pid){
    	$cdata = $this->getAllCats();
    	$temp = array();
    	$fz = false;
    	$dept = 0;
    	foreach($cdata as $value){
    		if($value['id'] == $pid){    			
    			array_push($temp,$value);
    			$fz=true;
    			$dept = $value['depth'];    			
    		}else{
    			//循环到父类的子类
    			if($fz && $dept<$value['depth']){
    				array_push($temp,$value);
    			}
    			if($fz && $dept==$value['depth']){
    				return $temp;
    			}
    			
    	  }
    	}
    	return $temp;
    }
    
    //获得顺序排列的所有分类并缓存到S('catDatas')
    public function getAllCats(){
    	if(!S('catDatas')){
    		 $data = $this->order('sort')->findAll();
    		 S('catDatas',$data);
    		 
    		 $this->_dgcat();
    		 
    		 S('catDatas',$this->catdata);
    	}
    	
    	return S('catDatas');
    	
    }
    
    
    //递归函数顺序排列分类
    private function _dgcat($pid=0){
    	$cdata = S('catDatas');
    	
    	foreach($cdata as $cd){
    		if($cd['pid'] == $pid){
    			 if($this->catdata){
    			 	 array_push($this->catdata,$cd);
    			 }else{
    			 	 $this->catdata[0] = $cd;
    			 }
    			 $this->_dgcat($cd['id']);
    	  }
    	}
    }
	
}
?>